package global

import (
	"github.com/sirupsen/logrus"
	"miao-server/structs/dto"
	"miao-server/structs/tables"
	"sync"
)

var Mu sync.Mutex

// DeviceMap 连接map
var DeviceMap = make(map[string]tables.Device)

// DeviceCache 设备缓存信息
var DeviceCache = make(map[int64]tables.Device)

// Policies 基础策略缓存
var Policies = make([]tables.Policy, 0)

// InstructCache 指令下发的时间缓存 key: 唯一码+cmd+argus
var InstructCache = make(map[string]int64)
var InstructResponseCache = make(map[string]dto.InstructResponseDto)

// HandUpCache 异常的举手信息
var HandUpCache = make(map[string]dto.HandsUpMsg)

func AddDeviceMap(m tables.Device) {
	Mu.Lock()
	defer Mu.Unlock()
	DeviceMap[m.UniqueValue] = m
}

func DelDeviceMap(key string) {
	Mu.Lock()
	defer Mu.Unlock()
	delete(DeviceMap, key)
}

// InitCache 初始化缓存
func InitCache() {
	var (
		ps  []tables.Policy
		ds  []tables.Device
		err error
	)
	err = DB.Model(&tables.Policy{}).Find(&ps).Error
	if err != nil {
		logrus.Error(err)
		return
	}
	Policies = ps
	err = DB.Model(&tables.Device{}).Find(&ds).Error
	if err != nil {
		logrus.Error(err)
		return
	}
	for _, item := range ds {
		DeviceCache[item.Id] = item
	}
}
